import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: DengJia
 * @Date: 2021/10/8 16:56
 * @Description: 消息服务的实现，收到订阅后根据id放到map，然后根据id删除
 */

public class MessageService implements Service {
    private static Map<String, Observice> observerMap = new ConcurrentHashMap<>();


    @Override
    public boolean addSub(Observice observice) {
        observerMap.put(observice.getId(), observice);
        System.out.printf("用户Id %s 姓名 %s 插入成功%n", observice.getId(), observice.getUsername());
        return true;
    }

    @Override
    public boolean removeSub(Observice observice) {
        if (observerMap.get(observice.getId()) == null) {
            System.out.printf("用户Id %s 姓名 %s 不存在 移除失败%n", observice.getId(), observice.getUsername());
            return false;
        }
        observerMap.remove(observice.getId());
        System.out.printf("用户Id %s 姓名 %s 已经移除 %n", observice.getId(), observice.getUsername());
        return true;
    }

    @Override
    public void push(Object obj) {
        if (null == obj) {
            return;
        }
        observerMap.forEach((k, v) -> v.getIt(obj)); // 推送时采用轮询推送
        System.out.println("所有消息推送完毕！");
    }
}
